package cn.school.service;

import cn.school.dao.SubjectDao;
import cn.school.entity.Page;
import cn.school.entity.Subject;
import cn.school.util.LogUtil;
import cn.school.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
public class SubjectService {

    public static final SubjectService INST=new SubjectService();

    public List<Subject> findALL() {
        SqlSession s = MyBatisUtil.get();
        try {
            SubjectDao dao = s.getMapper(SubjectDao.class);
            return dao.findALL();
        } finally {
            MyBatisUtil.close(s);
        }
    }

    public int add(Subject sub) {
        SqlSession s = MyBatisUtil.get();
        try {
            SubjectDao dao = s.getMapper(SubjectDao.class);
            return dao.add(sub);
        } finally {
            MyBatisUtil.close(s);
        }
    }

    public Page<Subject> search(int pageNo,int pageSize){
        SqlSession s = MyBatisUtil.get();
        try {
            SubjectDao dao = s.getMapper(SubjectDao.class);
            List<Subject> list = dao.search(pageNo, pageSize);
            int i = dao.searchTotal();
            return new Page<Subject>(pageNo,pageSize,i,list);
        } finally {
            MyBatisUtil.close(s);
        }
    }

    public boolean del(long id) {
        SqlSession s = MyBatisUtil.get();
        try {
            SubjectDao dao = s.getMapper(SubjectDao.class);
            int r = dao.del(id);
            return r > 0;
        }catch (Exception e){
            LogUtil.Log.error("删除失败",e);
            return false;
        } finally {
            MyBatisUtil.close(s);
        }
    }

    public Subject get(long id) {
        SqlSession s = MyBatisUtil.get();
        try {
            SubjectDao dao = s.getMapper(SubjectDao.class);

            return dao.get(id);
        }finally {
            MyBatisUtil.close(s);
        }
    }

    public int update(Subject sub) {
        SqlSession s = MyBatisUtil.get();
        try {
            SubjectDao dao = s.getMapper(SubjectDao.class);
            return dao.update(sub);
        } finally {
            MyBatisUtil.close(s);
        }
    }

    public boolean checkSubName(String name) {
        SqlSession s = MyBatisUtil.get();
        try {
            SubjectDao dao = s.getMapper(SubjectDao.class);
            return dao.checkSubName(name)>=1;
        } finally {
            MyBatisUtil.close(s);
        }
    }
}
